package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dto.UserSearchDTO;
import com.heima.search.pojo.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    BehaviorFeign behaviorFeign;

    @Autowired
    MongoTemplate mongoTemplate;


    /**
     * 查询历史记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        //1 参数检查
        ApUser user = AppThreadLocalUtils.getUser();
        //2 查询行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            log.info("ApUserSearchServiceImpl insert entryid is not null: {}", dto.getEntryId());
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 查询数据列表 按照时间倒序
        List<ApUserSearch> userSearchList = mongoTemplate.find(
                Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                        .with(Sort.by(Sort.Direction.DESC,"createdTime")),
                ApUserSearch.class);

        //4 返回结果
        return ResponseResult.okResult(userSearchList);
    }

    /**
     * 保存用户搜索历史记录
     *
     * @param dto
     */
    @Override
    @Async("taskExecutor")  //**** 异步方法执行
    public void insert(UserSearchDTO dto) {
        //1 参数检查
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //2 查询行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            log.info("ApUserSearchServiceImpl insert entryid is not null: {}", dto.getEntryId());
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3 根据实体id和关键词查询 历史记录
        ApUserSearch userSearch = mongoTemplate.findOne(
                Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                        .and("keyword").is(dto.getSearchWords())), ApUserSearch.class);
        //3.1 存在 则更新时间
        if (userSearch != null) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }

        //3.2 不存在 则创建新的历史记录（10条）
        List<ApUserSearch> userSearchList = mongoTemplate.find(
                Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime")),
                ApUserSearch.class);

        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setEntryId(behaviorEntry.getId());
        apUserSearch.setKeyword(dto.getSearchWords());
        if (userSearchList.size() < 10) {
            mongoTemplate.save(apUserSearch);
            return;
        }

        // 查询历史记录列表
        ApUserSearch lastUserSearch = userSearchList.get(userSearchList.size() - 1);
        mongoTemplate.findAndReplace(
                Query.query(Criteria.where("id").is(lastUserSearch.getId())), apUserSearch );

    }
}
